package com.changgou.core.helper;

import com.alibaba.fastjson.JSON;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Map;

/**
 * tokendecode  工具类获取当前请求的头对应的用户的信息
 */
public class RequestUtil {
    private static final String AUTHORIZE_TOKEN = "Authorization";

    /**
     * 获取用户的信息
     * @return
     */
    public static Map<String, String> getUserInfo() {
        //获取当前线程请求对象request对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            //获取登录的用户名 value 是一个字符串{“username_name”:"zhangsna"。。。。。。。}
            String value = requestAttributes.getRequest().getHeader(AUTHORIZE_TOKEN);
            Map<String, String> map = null;
            if (!StringUtils.isEmpty(value)) {
                map = JSON.parseObject(value, Map.class);
            }
            //获取用户名
            return map;
        }
        return null;
    }

    /**
     * 获取用户名
     * @return
     */
    public static String getUserName() {
        return getUserInfo() == null ? null : getUserInfo().get("user_name");
    }
}
